package www.com.library.app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/**
 * 异常调试信息打印类
 * @author Administrator
 *
 */
public class ExceptionLogger implements Thread.UncaughtExceptionHandler {
    /**
     * 是否允许保存crash日志，true保存到本地和发送到ga，false则直接打印到后台
     */
	public static boolean allowSaveCrash = false;
	private Thread.UncaughtExceptionHandler defaultUEH;
	public static String sdPath = "";
	private String localPath = "";
	private SimpleDateFormat mDateFormat;
	
	private static ExceptionLogger instance = null;
	
	public static void registerException(String path){
		if(null == instance){
			instance = new ExceptionLogger();
		}
		sdPath = path;
		instance.localPath = sdPath + "/crash/";
		instance.init();
	}
	
	public void init(){
		this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);  
		this.mDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
	}
	
	 @Override
	public void uncaughtException(Thread t, Throwable e) {
		/* Handle the exception */
		 Log.e("ExceptionLogger", "程序已经出现异常，即将关闭应用进程！！！");
		 if(!allowSaveCrash){
			 defaultUEH.uncaughtException(t, e);
			 android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
		 }else{
			/* Dump exception */
			 dumpException(e);
		 }
	}
	
	/**
	 * 异常处理类
	 * @param e
	 */
	public void dumpException(Throwable e) {
		final Writer result = new StringWriter();
		final PrintWriter printWriter = new PrintWriter(result);
		e.printStackTrace(printWriter);
		String stacktrace = result.toString();
		printWriter.close();
		dumpException(stacktrace);
	}
	
	/**
	 * 异常处理类
	 * @param stacktrace
	 */
	public void dumpException(String stacktrace) {
		String timestamp = mDateFormat.format(new Date());
//		AppTracker.sendExceptionTrack(stacktrace);
		String filename = timestamp + ".txt";

		if (localPath != null) {
			// create a File object for the parent directory
			File directory = new File(localPath);
			if (!directory.exists()) {
				if (!directory.mkdirs()) {
					// have the object build the directory structure, if needed.
					Log.e("ExceptionLogger",
							"Problem creating Image folder -> " + localPath);
				}
			}

			writeToFile(stacktrace, filename);
		}

		/* Start crash report activity */
		// 提示信息给用户
		new Thread() {
			@Override
			public void run() {
				try {
					Logger.e("dumpException线程id = " + android.os.Process.myTid());
					Looper.prepare();
					Toast.makeText(AppActivities.getSingleton().currentActivity(),"对不起，程序发生错误。\\n已将错误讯息记录！",Toast.LENGTH_LONG).show();
					Looper.loop();
				} catch (Exception e) {
				}
			}
		}.start();
		try {
			Thread.sleep(500);
		} catch (InterruptedException ex) {
		}
		System.exit(0);
	}

	/**
	 * 异常信息写入文件
	 * @param stacktrace
	 * @param filename
	 */
	private void writeToFile(String stacktrace, String filename) {
		try {
			BufferedWriter bos = new BufferedWriter(new FileWriter(localPath + filename));
			bos.write(stacktrace);
			bos.flush();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
